//
//  StaffTimeSelectViewController.m
//  QRMaster
//
//  Created by myApple on 15/7/24.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

enum
{
    KCSTAFF_TIMES_SELECTONE = 1340,
    KCSTAFF_TIMES_SELECTTWO,
    KCSTAFF_TIMES_SELECTTHRESS
};

#import "StaffTimeSelectViewController.h"
#import "AllocateBulidingModel.h"
#import "AllocateFloorModel.h"
#import "AllocateRoomModel.h"
#import "RequestNetWork.h"
#import "PromptInfoView.h"
#import "AllocateFloorCell.h"
#import "AllocateBulidingHeaderView.h"
#import "TimeRoomViewController.h"
#import "setTimeModel.h"
#import "Reachability.h"
#import "staffTimeCell.h"
#import "OpertionPlist.h"
#import "RoomDataProcess.h"
#import "ItemModel.h"
#import "AllocateFloorCell.h"
#import "staffRoomTimeCell.h"
#import "RoomBaseModel.h"
#import "EditStaffTimeView.h"
#import "TimeRoomViewController.h"
#import "SetStaffRoomTimeController.h"
#import "SetTimeByBuildController.h"


@interface StaffTimeSelectViewController ()<UITableViewDataSource,UITableViewDelegate,EditStaffTimeViewDelegate>
{
    UITableView * roomTableView;
    NSArray * displayDataArray;

    NSMutableArray * allTimeArray;
    
    UIView * backView;
    EditStaffTimeView * editBackView;
    NSMutableArray * bulidingArray;
    
    NSMutableArray * selectRoomArray;//被选中的房间
    BOOL flag;
    NSArray * weekData;
    RoomDataProcess * dataProcess;
    
    UIView * promtView;//提示view
    UILabel * promtLabel;
    UIView * promtnNoRoomView;//没有房间的提示操作
    UIImageView * editImageView;
    UILabel * editLabel;
}

@end

@implementation StaffTimeSelectViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dataProcess = [[RoomDataProcess alloc]init];
        weekData = @[NSLocalizedString(@"Sunday", nil),NSLocalizedString(@"Monday", nil),NSLocalizedString(@"Tuesday", nil),NSLocalizedString(@"Wednesday", nil),NSLocalizedString(@"Thursday", nil),NSLocalizedString(@"Friday", nil),NSLocalizedString(@"Saturday", nil)];
        bulidingArray = [[NSMutableArray alloc]init];
        allTimeArray = [[NSMutableArray alloc]init];
        selectRoomArray = [[NSMutableArray alloc]init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColorFromRGB(0xebebeb);
    self.title = NSLocalizedString(@"setTime", nil);
    [self prepareTabelView];
    [self preparePromtView];
    [self prepareViewWithNoRoom];
    [self prepareNavBtn];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    editImageView.hidden = NO;
    [bulidingArray removeAllObjects];
    [allTimeArray removeAllObjects];
    [self prepareTimeData];
    [self prepareData];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    editImageView.hidden = YES;
}

#pragma mark ---------没有开启时间周期的提示
-(void)preparePromtView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = ScreenHeight - y;
    
    promtView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    promtView.backgroundColor = RGBA(237, 238, 241, 1);
    promtView.userInteractionEnabled = YES;
    promtView.hidden = YES;
    [self.view addSubview:promtView];
    UITapGestureRecognizer * refreshPromtView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickPromtView)];
    [promtView addGestureRecognizer:refreshPromtView];
    
    x = 20;
    y = promtView.frame.size.height / 2.0 - 30;
    width = promtView.frame.size.width- 40;
    height = 60;
    promtLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    promtLabel.text = NSLocalizedString(@"disableTime", nil);
    promtLabel.font = [UIFont systemFontOfSize:14.0];
    promtLabel.numberOfLines = 0;
    promtLabel.textAlignment = NSTextAlignmentCenter;
    [promtView addSubview:promtLabel];

}

-(void)clickPromtView
{
    [bulidingArray removeAllObjects];
    [allTimeArray removeAllObjects];
    [self prepareTimeData];
    [self prepareData];
}

#pragma mark --------编辑
-(void)prepareNavBtn
{
    editImageView = [[UIImageView alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH - 66, 2, 50, 40)];
    editImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer * editTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(edit)];
    [editImageView addGestureRecognizer:editTap];
    [self.navigationController.navigationBar addSubview:editImageView];
    
    editLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 50, 20)];
    editLabel.text = @"编辑";
    editLabel.textColor = UIColorFromRGBAndA(0x7dc234, 1);
    editLabel.font = [UIFont systemFontOfSize:15.0];
    editLabel.textAlignment = NSTextAlignmentRight;
    [editImageView addSubview:editLabel];
    
    editBackView = [[EditStaffTimeView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT)];
    editBackView.backgroundColor = [UIColor clearColor];
    editBackView.delegate = self;
    editBackView.hidden = YES;
    UITapGestureRecognizer * hiddenEditTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenEditView)];
    [editBackView addGestureRecognizer:hiddenEditTap];
    [self.view addSubview:editBackView];
}

-(void)hiddenEditView
{
    editBackView.hidden = YES;
    editLabel.text = @"编辑";
}

-(void)edit
{
    editBackView.hidden = !editBackView.hidden;
    if (editBackView.hidden) {
        editLabel.text = @"编辑";
    }
    else
    {
         editLabel.text = @"取消";
    }
}

#pragma mark --------EditStaffTimeViewDelelgate
-(void)EditStaffTimeView:(NSInteger)selectIndex
{
    editBackView.hidden = YES;
    editLabel.text = @"编辑";
    switch (selectIndex) {
        case 0:
        {
            TimeRoomViewController * vc = [[TimeRoomViewController alloc]init];
            vc.staffTimeRoomArray = [dataProcess getRoomDataAllocate];
            vc.managerTimeArray = allTimeArray;
            vc.staffId = _staffUid;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 1:
        {
            SetStaffRoomTimeController * ssrtc = [[SetStaffRoomTimeController alloc]init];
            ssrtc.FloorInfoArray = [dataProcess getFloorDataAllocate];
            ssrtc.managerTimeArray = allTimeArray;
            ssrtc.staffId = _staffUid;
            [self.navigationController pushViewController:ssrtc animated:YES];
        }
            break;
        case 2:
        {
            SetTimeByBuildController * stbbc = [[SetTimeByBuildController alloc]init];
            stbbc.buildInfoArray = [dataProcess getBuildDataAllocate];
            stbbc.allTimeArray = allTimeArray;
            stbbc.staffId = _staffUid;
            [self.navigationController pushViewController:stbbc animated:YES];
        }
            break;
        default:
            break;
    }
}

#pragma mark ---------请求房间数据
-(void)prepareData
{
    if ([self IsHaveNetwork]) {
        return;
    }
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:_communityId forKey:@"communityId"];
    [postDict setValue:_staffUid forKey:@"userId"];
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(GETONESELFROOM) params:postDict block:^(id downLoadData, id error)
     {
         NSArray * data = [downLoadData objectForKey:@"data"];
         if (data) {
              [bulidingArray removeAllObjects];
             bulidingArray = [[dataProcess dataProcess:data] mutableCopy];
             displayDataArray = [bulidingArray copy];
             if (bulidingArray.count == 0) {
                 promtnNoRoomView.hidden = NO;
             }
             [roomTableView reloadData];
         }
         else
         {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
         }
     }
     ];

}


#pragma mark --------没有房间的提示
-(void)prepareViewWithNoRoom
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = self.view.frame.size.height;
    float width;
    float height;
    
    promtnNoRoomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    promtnNoRoomView.backgroundColor = RGBA(237, 238, 241, 1);
    promtnNoRoomView.hidden = YES;
    [self.view addSubview:promtnNoRoomView];
    
    NSString * imgPath = [[NSBundle mainBundle]pathForResource:@"没有设置默认房卡" ofType:@"png"];
    UIImage * promImg = [UIImage imageWithContentsOfFile:imgPath];
    height= promImg.size.height * ScreenWidth / 3.0 /promImg.size.width;
    width = ScreenWidth / 3.0;
    UIImageView * promImgView = [[UIImageView alloc]initWithFrame:CGRectMake((self.view.frame.size.width - width)/ 2.0, (self.view.frame.size.height - height)/ 2.0 - 64, width, height)];
    promImgView.image = promImg;
    [promtnNoRoomView addSubview:promImgView];
    
    
    UILabel * promtTextLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, promImgView.frame.size.height /2.0+promImgView.frame.origin.y + 74, ScreenWidth - 100, 60)];
    promtTextLabel.text = NSLocalizedString(@"allocateRoom", nil);
    promtTextLabel.textColor = RGBA(211, 211, 211, 1);
    promtTextLabel.textAlignment = NSTextAlignmentCenter;
    promtTextLabel.numberOfLines = 0;
    promtTextLabel.font = [UIFont systemFontOfSize:16.0];
    [promtnNoRoomView addSubview:promtTextLabel];
    
}


#pragma mark -----------请求时间周期
-(void)prepareTimeData
{
    if ([self IsHaveNetwork]) {
        return;
    }
    [allTimeArray removeAllObjects];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:_communityId forKey:@"communityId"];
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(GETSTAFFCOMMUNITYTIME) params:postDict block:^(id downLoadData, id error)
     {
         if ([downLoadData objectForKey:@"data"]) {
             NSString * timeFlag = [[downLoadData objectForKey:@"data"] objectForKey:@"flag"];
             if ([timeFlag integerValue] == 1) {
                 NSArray * list = [[downLoadData objectForKey:@"data"] objectForKey:@"list"];
                 for (NSDictionary * dict in list) {
                     setTimeModel * model = [[setTimeModel alloc]init];
                     model.beginTime = [dict objectForKey:@"startTime"];
                     model.endTime = [dict objectForKey:@"endTime"];
                     model.weekInfo = [dict objectForKey:@"cycleString"];
                     model.timeId = [dict objectForKey:@"id"];
                     switch ([model.timeId integerValue]) {
                         case 47:
                             model.timeImage = [UIImage imageNamed:@"roomTime1"];
                             break;
                         case 48:
                             model.timeImage = [UIImage imageNamed:@"roomTime2"];
                             break;
                         case 49:
                             model.timeImage = [UIImage imageNamed:@"roomTime3"];
                             break;
                             
                         default:
                             break;
                     }
                     [allTimeArray addObject:model];
                 }
                 if (allTimeArray.count < 1) {
                     promtView.hidden = NO;
                     promtLabel.text = NSLocalizedString(@"openAllTime", nil);
                     return ;
                 }
             }
             else
             {
                 promtView.hidden = NO;
                 return;
             }
             flag = [timeFlag boolValue];
         }
         else
         {
             [PromptInfoView showMessage:[error objectForKey:@"info"]];
         }
         [roomTableView reloadData];
     }
    ];
}


#pragma mark -----------准备tableview视图
-(void)prepareTabelView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = self.view.frame.size.height;
    float x = 0;
    float y = 5;
    float width = ScreenWidth;
    float height = ScreenHeight - y - 64;
    
    roomTableView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStylePlain];
    roomTableView.delegate = self;
    roomTableView.dataSource = self;
    roomTableView.tableFooterView = [[UIView alloc]init];
    roomTableView.separatorStyle = NO;
    [self.view addSubview:roomTableView];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return displayDataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RoomBaseModel * nextModel  = nil;
    if (displayDataArray.count - 1 > indexPath.row) {
        nextModel = displayDataArray[indexPath.row + 1];
    }
    RoomBaseModel * model = [displayDataArray objectAtIndex:indexPath.row];
    if (model.nodeType == NodeTypeGroup) {
        AllocateFloorCell *cell = [AllocateFloorCell cellWithTableView:tableView];
        [cell setData:(ItemModel *) model];
        return cell;
    }
    else
    {
        staffRoomTimeCell *cell = [staffRoomTimeCell cellWithTableView:tableView];
        cell.allTimeArray = allTimeArray;
        [cell setData:(AllocateRoomModel *)model];
        if (indexPath.row == displayDataArray.count - 1) {
            cell.isLastRow = YES;
        }
        else if(nextModel.nodeLevel == 1 && model.nodeLevel == 3)
        {
            cell.isLastRow = YES;
        }
        else
        {
            cell.isLastRow = NO;
        }
        return cell;
    }}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    RoomBaseModel * model = displayDataArray[indexPath.row];
    if (model.nodeLevel == 3) {
        return;
    }
    model.isExpanded = !model.isExpanded;
    model.isClick = YES;
    [self reloadDisplayArray];
}

#pragma mark --------点击刷新
-(void)reloadDisplayArray
{
    NSMutableArray * tmpList = [[NSMutableArray alloc]init];
    for (ItemModel * model in bulidingArray) {
        if (model.isExpanded) {
            [self addData:model toArray:tmpList];
        }
        else
        {
            [tmpList addObject:model];
        }
    }
    displayDataArray = [[NSArray arrayWithArray:tmpList] mutableCopy];
    [roomTableView reloadData];
}

-(void)addData:(ItemModel *)model toArray:(NSMutableArray *)tmpList
{
    [tmpList addObject:model];
    for (ItemModel * floorModel in model.itemChildrenArray) {
        [tmpList addObject:floorModel];
        if (floorModel.isExpanded) {
            for (AllocateRoomModel * roomModel in floorModel.itemChildrenArray) {
                [tmpList addObject:roomModel];
            }
        }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
